/*
 * This file is part of Shopping Lists Organizer software
 *
 * Copyright (C) 2011 Denis Kvita <dkvita@gmail.com>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, see <http://www.gnu.org/licenses/>.
 */

#include <QtGui>

#include "shopeditor.h"
#include "shopmodel.h"

shopEditor::shopEditor(QWidget *parent) :
	QWidget(parent)
{
	setWindowTitle(tr("Shop Editor"));

	QSettings cfg(qApp->property("dataDir").toString()+"/settings.ini", QSettings::IniFormat);

	shopD= new shopModel;

	shopP= new QSortFilterProxyModel;
	shopP->setSourceModel(shopD);
	shopP->setFilterKeyColumn(0);
	shopP->setFilterRegExp(QRegExp("*", Qt::CaseInsensitive, QRegExp::WildcardUnix));

	shopV= new QTableView;
	shopV->setModel(shopP);
	shopV->verticalHeader()->setDefaultSectionSize(22);
	shopV->verticalHeader()->setMovable(true);
	shopV->horizontalHeader()->setFixedHeight(22);
	shopV->horizontalHeader()->setSortIndicatorShown(true);
	shopV->horizontalHeader()->setMovable(true);
	shopV->horizontalHeader()->setContextMenuPolicy(Qt::ActionsContextMenu);
	shopV->horizontalHeader()->setTextElideMode(Qt::ElideMiddle);
	shopV->setSortingEnabled(true);
	shopV->setEditTriggers(QAbstractItemView::DoubleClicked|QAbstractItemView::EditKeyPressed|QAbstractItemView::AnyKeyPressed);
	shopV->setSelectionBehavior(QAbstractItemView::SelectItems);
	shopV->setSelectionMode(QAbstractItemView::SingleSelection);
	connect(shopV->selectionModel(),SIGNAL(selectionChanged(QItemSelection,QItemSelection)),this,SLOT(onSelectionChanged(QItemSelection,QItemSelection)));

	QByteArray hDat= QByteArray::fromBase64(cfg.value("/shopEditor/header").toByteArray());
	if(!hDat.isEmpty()){
		hDat= qUncompress(hDat);
		if(!hDat.isEmpty()) shopV->horizontalHeader()->restoreState(hDat);
	}

	QAction *a;
	for(int i=0; i<shopD->columnCount(); i++){
		a= new QAction(shopD->headerData(i,Qt::Horizontal).toString(),shopV->horizontalHeader());
		a->setData(i);
		a->setCheckable(true);
		a->setChecked(shopV->horizontalHeader()->isSectionHidden(i) ? Qt::Unchecked : Qt::Checked );
		connect(a, SIGNAL(triggered(bool)), this, SLOT(onHeaderSectionShow(bool)));
		shopV->horizontalHeader()->addAction(a);
	}

	shopFilterV= new QComboBox;
	shopFilterV->setEditable(true);
	shopFilterV->setInsertPolicy(QComboBox::InsertAfterCurrent);
	shopFilterV->setDuplicatesEnabled(false);
	shopFilterV->addItem("*");
	shopFilterV->completer()->setCompletionMode(QCompleter::PopupCompletion);
	shopFilterV->setToolTip(tr("enter a shop title's filter <br><b>'*'</b>- imply any number of any characters <br><b>'?'</b>- imply one any character"));
	connect(shopFilterV->lineEdit(), SIGNAL(textEdited(QString)), this, SLOT(onShopFilterEdited(QString)));
	connect(shopFilterV, SIGNAL(currentIndexChanged(int)), this, SLOT(onShopFilterChanged(int)));

	addShop= new QToolButton;
	addShop->setIcon(QIcon(":/img/add.png"));
	addShop->setToolTip(tr("add shop"));
	addShop->setAutoRaise(true);
	connect(addShop, SIGNAL(clicked()), this, SLOT(onAddShop()));

	remShop= new QToolButton;
	remShop->setIcon(QIcon(":/img/rem.png"));
	remShop->setToolTip(tr("delete shop"));
	remShop->setAutoRaise(true);
	remShop->setEnabled(false);
	connect(remShop, SIGNAL(clicked()), this, SLOT(onRemoveShop()));


	QLabel *sumPlanL= new QLabel(tr("Total planned: "));
	sumPlanL->setAlignment(Qt::AlignRight|Qt::AlignVCenter);
	sumPlanV= new QLabel;
	QFont bFnt= font();
	bFnt.setBold(true);
	sumPlanV->setFont(bFnt);

	QLabel *sumBuyL= new QLabel(tr("Total spent: "));
	sumBuyL->setAlignment(Qt::AlignRight|Qt::AlignVCenter);
	sumBuyV= new QLabel;
	sumBuyV->setFont(bFnt);


	connect(this, SIGNAL(guiControlsSwitch(bool)), remShop, SLOT(setEnabled(bool)));

	connect(shopD, SIGNAL(totalChanged()), this, SLOT(updateTotals()));

	QHBoxLayout *shopLt= new QHBoxLayout;
	shopLt->addWidget(addShop);
	shopLt->addWidget(remShop);
	shopLt->addWidget(shopFilterV,1);
	shopLt->setMargin(0);
	shopLt->setSpacing(2);

	QHBoxLayout *sumLt= new QHBoxLayout;
	sumLt->addWidget(sumPlanL);
	sumLt->addWidget(sumPlanV);
	sumLt->addSpacing(20);
	sumLt->addWidget(sumBuyL);
	sumLt->addWidget(sumBuyV);
	sumLt->addStretch(1);
	sumLt->setMargin(0);
	sumLt->setSpacing(2);

	QVBoxLayout *mlt= new QVBoxLayout;
	mlt->addLayout(shopLt);
	mlt->addWidget(shopV,1);
	mlt->addLayout(sumLt);
	mlt->setMargin(3);

	setLayout(mlt);
}

void shopEditor::onAddShop()
{
	QModelIndex idx= shopD->addEmpty();
	if(idx.isValid()){
		shopV->clearSelection();
		shopV->setCurrentIndex(shopP->mapFromSource(idx));
		shopV->scrollTo(shopP->mapFromSource(idx));
	}
}

void shopEditor::onRemoveShop()
{
	if(!shopV->selectionModel()->hasSelection()) return;

	if(QMessageBox::question(this,tr("Delete shop"),
							 tr("Do you want to delete the information about shop <b>'")
							 +shopD->data(shopD->index(selectedShop(),0)).toString()+tr("'</b>?"),
							 QMessageBox::Ok, QMessageBox::Cancel) != QMessageBox::Ok) return;

	shopD->rem(selectedShop());
}

void shopEditor::onShopFilterEdited(const QString &text)
{
	shopP->setFilterRegExp(QRegExp(text,Qt::CaseInsensitive,QRegExp::Wildcard));
	updateTotals();
}

void shopEditor::onShopFilterChanged(int index)
{
	shopP->setFilterRegExp(QRegExp(shopFilterV->itemText(index),Qt::CaseInsensitive,QRegExp::Wildcard));
	updateTotals();
}

int shopEditor::selectedShop()
{
	return shopP->mapToSource(shopV->selectionModel()->selectedIndexes().at(0)).row();
}

void shopEditor::saveSettings()
{
	QSettings cfg(qApp->property("dataDir").toString()+"/settings.ini", QSettings::IniFormat);
	cfg.setValue("/shopEditor/header",qCompress(shopV->horizontalHeader()->saveState()).toBase64());
	cfg.setValue("/shopEditor/filter",shopFilterV->currentText());
}

void shopEditor::updateData()
{
	shopD->restore();
	updateTotals();
}

void shopEditor::updateTotals()
{
	double tCostP=0,tCost=0;
	for(int i=0; i<shopP->rowCount(); i++){
		tCostP+= shopP->mapFromSource(shopD->index(shopP->mapToSource(shopP->index(i,0)).row(),5)).data().toDouble();
		tCost+= shopP->mapFromSource(shopD->index(shopP->mapToSource(shopP->index(i,0)).row(),6)).data().toDouble();
	}
	sumPlanV->setText(QString::number(tCostP,'f',2));
	sumBuyV->setText(QString::number(tCost,'f',2));

}

void shopEditor::restore()
{
	QSettings cfg(qApp->property("dataDir").toString()+"/settings.ini", QSettings::IniFormat);
	shopFilterV->clear();
	shopFilterV->addItem(tr("*"));
	QString flt= cfg.value("/shopEditor/filter").toString();
	if(flt!="*"){
		shopFilterV->addItem(flt);
		if(!flt.isEmpty())shopFilterV->setCurrentIndex(shopFilterV->findText(flt));
	}

	updateData();
}

void shopEditor::onHeaderSectionShow(bool isShow)
{
	QAction *act= qobject_cast<QAction*>(sender());
	if(act == 0) return;
	shopV->horizontalHeader()->setSectionHidden(act->data().toInt(),!isShow);
}

void shopEditor::onSelectionChanged(const QItemSelection &selected, const QItemSelection &deselected)
{
	if(shopV->selectionModel()->hasSelection()) emit guiControlsSwitch(true);
	else emit guiControlsSwitch(false);
}
